package com.hncboy.chatgpt.front.controller;

import cn.hutool.core.date.DateUtil;
import com.hncboy.chatgpt.base.handler.response.R;
import com.hncboy.chatgpt.front.api.chat0714.OpenAiStreamClientS;
import com.hncboy.chatgpt.front.api.chat0714.Subscription;
import com.hncboy.chatgpt.front.domain.request.ChatProcessRequest;
import com.hncboy.chatgpt.front.service.ChatMessageService;
import com.hncboy.chatgpt.front.util.AStringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;


/**
 * @author hncboy
 * @date 2023-3-22
 * 聊天相关接口
 */
@AllArgsConstructor
@Tag(name = "聊天相关接口")
@RestController("FrontChatMessageController")
@RequestMapping("/chat_message")
@Slf4j
public class ChatMessageController {

    private final ChatMessageService chatMessageService;

    private OpenAiStreamClientS openAiClient;

    @Operation(summary = "发送消息")
    @PostMapping("/send")
    public ResponseBodyEmitter sendMessage(@RequestBody @Validated ChatProcessRequest chatProcessRequest, HttpServletResponse response) {
        // TODO 后续调整
        String systemMessage = chatProcessRequest.getSystemMessage();
        if (AStringUtils.isEmpty(systemMessage)){
            chatProcessRequest.setSystemMessage("你是ChatGPT，一个由OpenAI训练的大型语言模型。尽可能提供详细和人性化的回答。\\知识截断点: 2021-09-01\\当前日期：".concat(DateUtil.today()));
        }
        //(简明扼要)You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date:
        //(详细人性化)You are ChatGPT, a large language model trained by OpenAI. Provide as detailed and humane a response as possible. \\nKnowledge cutoff: 2021-09-01\nCurrent date:
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        ResponseBodyEmitter responseBodyEmitter = chatMessageService.sendMessage(chatProcessRequest);
        return responseBodyEmitter;
    }


    @Operation(summary = "查询余额")
    @GetMapping("/CheckBalance")
    public R<String> CheckBalance() {
//        Subscription subscription = ApiKeyChatClientBuilder.buildOpenAiStreamClient().subscription();
        Subscription subscription = openAiClient.subscription();
        log.info("用户名：{}", subscription.getAccountName());
        log.info("用户总余额（美元）：{}", subscription.getHardLimitUsd());
        return R.data(String.valueOf(subscription.getHardLimitUsd()));
    }
}
